import { ContractManageAPI } from '../common/type';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useContext, useMemo, useState } from 'react';
import { ConractControllerContext, IContractsActionEnum } from '../common';
import { OpenProcureoModal } from './OpenProcureoModal';
import { getDescrConfig, ntkoQueryParams } from '../mconfig';
import { DescriptionsType } from '@/components/DescriptionsType';
import { OpenContractTempModal } from './OpenContractTempModal';
import { changeNumMoneyToChinese, wordHandChildParam, wordToChildParams, getKeyRouter } from '@/utils';
import { OpenCounterpartModal } from './OpenCounterpartModal';
import { OpenContractMainBodyModal } from './OpenContractMainBodyModal';
import { UpdateContractBottom } from './UpdateContractBottom';
import { saveToURLWordService } from '../services';
import { NtkoPlugin } from '@/common/NtkoPluginType';
import { getBaseUrl } from '@/services/urlconst';
import { OpenMaterialModal } from './OpenMaterialModal';
import { OpenDepartmentModal } from './OpenDepartmentModal';
import UpdateProjectModal from './ProjectModal';
// import { WorkflowChedkRecord } from '@/components/WorkflowCommon';
import { readReadShowFileService } from '@/services/BaseLayout';
import { history } from 'umi';

export const UpdateContrractInfo: React.FC<ContractManageAPI.IUpdateContrractInfo> = ({ changeTextInfo, setTabsInfoPaneInfo, onValuesChange, loadMapInfo }) => {
  /** 引入上下文 */
  const {
    styleFixCls,
    contractForm,
    contarctJsonList,
    contractDispatch,
    updteAddOrEdit: { addContractRun, editContractRun, editRecordContractRun, submitRecordContractRun, addAndSubmitContractRun },
    contractDetailInfo,
    curRes,
    locationState,
  } = useContext(ConractControllerContext);

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
    // readReadShowFileRun({ fieldPath: `http://222.186.101.211:20103${fieldUrl}` });
  };

  /** 打开采购申请 */
  const [applyBoolean, setApplyBoolean] = useState<boolean>(false);

  /** 选择合同范本 */
  const [openTempModal, setOpenTempModal] = useState<boolean>(false);

  /** 打开合同主体弹框 */
  const [openSubjectModal, setOpenSujbectModal] = useState<boolean>(false);

  /** 超预算后不能进行其他操作 */
  const [isBudgetNotBtn, setIsBudgetNotBtn] = useState<boolean>(false);

  /** 选择相对方 */
  const [openCounterpartObj, setOpenCounterpartObj] = useState<boolean>(false);

  /** 打开选择物料列表 */
  const [openMaterialModal, setOpenMaterialModal] = useState<boolean>(false);

  /** 保存在线编辑权限 */
  const [saveNtkoQuery, setSaveNtkoQuery] = useState<Record<string, any>>({
    filedUrl: '',
    ntkoWordUrl: '',
  });

  /** 打开资金来源弹框 */
  const [projectModal, setProjectModal] = useState<null | Record<string, any>>();

  /** 选择申请人 */
  // const [openOwnerDeptModal, setOpenOwnerDeptModal] = useState<Record<string, any>>({
  //   isShowModal: false,
  //   checkTypeInfo: {}
  // })

  /** FORM 表单改变事件 */
  const onValuesChange_ = (changeValues: Record<string, any>) => {
    const changeKeyStr: string = Object.keys(changeValues)?.toString();
    if (changeKeyStr == 'sumInTax') {
      const maxNumStr: string = changeNumMoneyToChinese(changeValues?.[changeKeyStr]);
      methods?.setFieldsValue({
        sumInTaxCN: maxNumStr,
      });
    } else if (changeKeyStr == 'budgetFlag') {
      if (changeValues?.budgetFlag == 0 && isBudgetNotBtn) {
        setIsBudgetNotBtn(false);
      } else if (changeValues?.budgetFlag == 1 && !isBudgetNotBtn) {
        setIsBudgetNotBtn(true);
      }
    }

    // 编辑
    // if (contractDetailInfo?.id) {
    // const changeKeyStr: string = Object.keys(changeValues)?.toString(); //获取变更字段名
    const allFormValues: Record<string, any> = contractForm?.getFieldsValue(); //获取全部填入表单数据
    if (changeKeyStr == 'processList' || changeKeyStr == 'detailList' || changeKeyStr == 'attachList') {
      const changeKeyList: Record<string, any>[] = allFormValues?.[changeKeyStr]; //获取变更的数据源
      const changeKeyIndx: number = changeValues?.[changeKeyStr]?.length - 1;
      if (changeKeyList[changeKeyIndx]['id']) {
        changeKeyList[changeKeyIndx]['modifyFlag'] = '1';
      } else {
        changeKeyList[changeKeyIndx]['modifyFlag'] = '0';
      }
      // if (changeKeyStr == 'processList' && allFormValues?.['sumInTax']) {
      //   // changeKeyList[changeKeyIndx]['paySum'] = (allFormValues?.['sumInTax'] * changeKeyList[changeKeyIndx]['payNum']) / 100;
      //   // const num = (changeKeyList[changeKeyIndx]['paySum'] / allFormValues?.['sumInTax']) * 100;

      //   // changeKeyList[changeKeyIndx]['payNum'] = num.toFixed(2);
      // }

      let newChangeList: Record<string, any>[] = changeKeyList?.filter((item: any) => {
        //已有标记数据
        return (item?.id || item?.key) && item?.modifyFlag != null;
      });

      const newFormJsonList: Record<string, any>[] = contarctJsonList[changeKeyStr]?.length > 0 ? contarctJsonList[changeKeyStr] : [];

      newFormJsonList?.forEach((delItem: any) => {
        if (delItem?.modifyFlag == '2') {
          newChangeList?.push(delItem);
        }
      });

      contractDispatch({
        //保存标记后的代码
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {
          ...contarctJsonList,
          [changeKeyStr]: newChangeList,
        },
      });

      contractForm?.setFieldsValue({
        [changeKeyStr]: allFormValues?.[changeKeyStr],
      });
    }

    if (changeKeyStr == 'payStyle') {
      let newPaylist: Record<string, any>[] = [];
      contractDetailInfo?.processList?.forEach((itemPay: any) => {
        const itemInfo: Record<string, any> = {
          ...itemPay,
          modifyFlag: '2',
        };
        newPaylist?.push(itemInfo);
      });

      contractDispatch({
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {
          ...contarctJsonList,
          processList: [...newPaylist],
        },
      });
    }
    // }
  };

  /** 保存文件接口回调 */
  const saveToUrlWordCallback = (res: any) => {
    const messageObj = {
      msgFlag: res?.msgFlag,
      msgText: res?.msg,
      msgType: 'uploadFiledRequest',
    };
    wordToChildParams(ntkoBrowser, saveNtkoQuery?.ntkoWordUrl, messageObj);
  };

  /** 保存文件接口 */
  const { wordSaveToURLRun } = saveToURLWordService(saveToUrlWordCallback);

  /** 保存文件回调 */
  const ntkoCallback = (childValue) => {
    const childBase = JSON.parse(childValue);
    if (childBase?.baseUrl && childBase?.baseObj) {
      const fieldUrl: string = childBase?.baseUrl?.split(getBaseUrl());
      wordSaveToURLRun({
        ...childBase,
        baseUrl: fieldUrl?.[1],
      });
    }
  };

  /** 引入在线预览 */
  const ntkoBrowser = useMemo(() => {
    const { ntkoBrowser } = NtkoPlugin(ntkoCallback);
    return ntkoBrowser;
  }, []);

  /** 点击在线预览文件 */
  const onNtkoReadWord = (urlName: string, urlObj: Record<string, any>, onlyRead?: boolean) => {
    const { filedUrl, ntkoWordUrl } = ntkoQueryParams(urlObj, curRes, urlName, onlyRead);
    setSaveNtkoQuery({
      filedUrl,
      ntkoWordUrl,
    });
    const childStr = wordHandChildParam(urlObj);

    const extensBool = ntkoBrowser.ExtensionInstalled();
    if (extensBool) {
      ntkoBrowser?.openWindow(ntkoWordUrl, false, '', childStr);
    }
  };

  //拆解参数
  function parseQuery(query) {
    return query.split('&&').reduce((acc, pair) => {
      const [key, value] = pair.split('=');
      acc[key] = value;
      return acc;
    }, {});
  }

  //进入采购页面
  const enterPurchProject = (record) => {
    if (curRes?.['/purchaseSourceController/getBidById']) {
      const purchaseURL = parseQuery(record?.purchaseURL);
      history.push({
        pathname: `/purchaseSourceController/getBidById/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          type: 'detail',
          info: purchaseURL,
          returnPathName: locationState?.pathname,
        },
      });
    }
  };

  /** 获取表单配置 */
  const { config, methods } = getDescrConfig({
    openApplyModal: setApplyBoolean,
    openTempModalFunc: setOpenTempModal,
    openSubjectModal: () => setOpenSujbectModal(true),
    changeTextInfo,
    onFormChange: onValuesChange || onValuesChange_,
    onNtkoReadWord,
    onOpenReadOfdWord,
    openCounterpartModal: setOpenCounterpartObj,
    setOpenMaterialModal,
    setProjectModal: () => setProjectModal({ isShow: true }),
    // setOpenOwnerDeptModal,
    enterPurchProject,
  });

  const saveProjectData = (res) => {
    contractForm?.setFieldsValue({
      projectCode: res.projectCode,
      projectName: res.projectName,
    });
  };

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '5px 20px' }}>
            <DescriptionsType config={config} onValuesChange={onValuesChange || onValuesChange_} />
          </ScrollBarLayout>
        </div>

        <UpdateContractBottom
          nextBtnShow={changeTextInfo?.isUnifiedText}
          isBudgetNotBtn={isBudgetNotBtn}
          setTabsInfoPaneInfo={setTabsInfoPaneInfo}
          addContractRun={addContractRun}
          editContractRun={editContractRun}
          editRecordContractRun={editRecordContractRun}
          submitRecordContractRun={submitRecordContractRun}
          addAndSubmitContractRun={addAndSubmitContractRun}
          requestType={false}
          loadMapInfo={loadMapInfo}
          position="bottom"
        />
      </div>

      {/* 提示框 */}
      {/* {openTipInfoModal?.showModal && (
        <TipsErrorModalNew
          ref={tipErrorModalRef}
          modalLoading={false}
          onClose={tipOnClose}
          modalOnOK={() => { }}
          tipTextColor="#000"
          modalTip={`合同类型修改后，需重新生成合同正文`}
        />
      )} */}

      {/* 选择物料列表 */}
      {openMaterialModal && (
        <OpenMaterialModal
          isShowModal={openMaterialModal}
          onClose={() => {
            setOpenMaterialModal(false);
          }}
        />
      )}

      {/* 选择申请 */}
      {applyBoolean && (
        <OpenProcureoModal
          onClose={() => {
            setApplyBoolean(false);
          }}
          contractFormName={methods}
        />
      )}

      {/* 打开合同范本 */}
      {openTempModal && (
        <OpenContractTempModal
          onClose={() => {
            setOpenTempModal(false);
          }}
          contractFormName={methods}
        />
      )}

      {/* 选择相对方 */}
      {openCounterpartObj && (
        <OpenCounterpartModal
          onClose={() => {
            setOpenCounterpartObj(false);
          }}
          openModal={openCounterpartObj}
        />
      )}

      {/* 选择合同主体 */}
      {openSubjectModal && (
        <OpenContractMainBodyModal
          onClose={() => {
            setOpenSujbectModal(false);
          }}
          contractFormName={methods}
        />
      )}

      {/* 选择资金来源 */}
      {projectModal && <UpdateProjectModal onSave={(res) => saveProjectData(res)} onClose={() => setProjectModal(null)} />}

      {/* 选择申请人 */}
      {/* {openOwnerDeptModal?.isShowModal && (
        <OpenDepartmentModal
          onClose={() => {
            setOpenOwnerDeptModal({
              isShowModal: false,
              checkTypeInfo: {}
            });
          }}
          checkTypeInfo={openOwnerDeptModal?.checkTypeInfo}
        />
      )} */}

      {/* 签订 */}
      {/* {openSignModalObjj?.isShowModal && (
        <ContractSignModal
          onClose={() => {
            setOpenSiginModalObj({
              isShowModal: false,
              selectRow: {},
            });
          }}
          selectRowInfo={openSignModalObjj?.selectRow}
        />
      )} */}
    </>
  );
};
